<?php

namespace app\model;

use think\Model;

class UuidRelation extends Model
{

	protected $connection = 'mysql';

	protected $pk = 'id';

	protected $name = 'uuid_relation';

	public static function getreid($uid, $ptype)
	{
		$res = self::getrelaarray($uid, $ptype);
		return $res['reid'];
	}

	public static function getrelaarray($uid, $ptype)
	{
		$query = self::where(['weid' => weid(), 'ptype' => $ptype, 'uid' => $uid])->whereNotNull('uuid')->where('uuid', '<>', '');
		$mob = $query->order('id desc')->find();

		$users = Users::where('uuid', $mob->uuid)->find();
		if (!empty($users)) {
			$res['uid'] = $users->id;
		}

		if (!empty($mob)) {
			if ($ptype == 'store') {
				$redata = Store::where('uuid', $mob->uuid)->find();
				$res['reid'] = $redata->id;
			}

			if ($ptype == 'tuanzhang') {
				$redata = Tuanzhang::where('uuid', $mob->uuid)->find();
				$res['reid'] = $redata->id;
			}

			if ($ptype == 'operatingcity') {
				$redata = Operatingcity::where('uuid', $mob->uuid)->find();
				$res['reid'] = $redata->id;
			}

			if ($ptype == 'technical') {
				$redata = Technical::where('uuid', $mob->uuid)->find();
				$res['reid'] = $redata->id;
			}

			UsersRelation::create([
				'weid' => weid(),
				'ptype' => $ptype,
				'reid' => (int) $res['reid'],
				'uid' => (int) $res['uid'],
				'mid' => $uid
			]);

			self::where([
				'weid' => weid(),
				'ptype' => $ptype,
				'uid' => $uid
			])->delete();

			return $res;
		}
	}

	public static function getuid($reid, $ptype)
	{
		if ($ptype == 'store') {
			$redata = Store::find($reid);
			$uuid = $redata->uuid;
		}

		if ($ptype == 'tuanzhang') {
			$redata = Tuanzhang::find($reid);
			$uuid = $redata->uuid;
		}

		if ($ptype == 'operatingcity') {
			$redata = Operatingcity::find($reid);
			$uuid = $redata->uuid;
		}

		if ($ptype == 'technical') {
			$redata = Technical::find($reid);
			$uuid = $redata->uuid;
		}
		if ($uuid) {
			$query = self::where(['weid' => weid(), 'uuid' => $uuid]);
			$mob = $query->order('id desc')->find();

			if (!empty($mob)) {
				return $mob->uid;
			}
		}
	}
}
